﻿using Microsoft.UI.Xaml.Data;

namespace DimensionsHelper.Client.WinUi.Views;

public sealed partial class TaskInformationPage : Page
{
    public TaskInformationPage()
    {
        ViewModel = App.GetService<TaskInformationViewModel>();
        ViewModel.RegisterProjectTaskChangedHandler(OnProjectTaskCollectionChanged);
        InitializeComponent();

        foreach (IProjectTask task in ViewModel.Tasks)
        {
            AddTabItem(task);
        }
    }

    public TaskInformationViewModel ViewModel
    {
        get;
    }


    private void OnProjectTaskCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems is [IProjectTask task, ..])
        {
            AddTabItem(task);
        }
    }


    private void AddTabItem(IProjectTask project)
    {
        TabViewItem tabViewItem = new()
        {
            CanDrag = false,
            IsClosable = project.CanRemove,
            Content = new TaskInformationDetailControl
            {
                ListDetailsMenuItem = project
            }
        };

        BindingOperations.SetBinding(tabViewItem, TabViewItem.HeaderProperty, new Binding
        {
            Source = project,
            Path = new PropertyPath(nameof(IProjectTask.DisplayName))
        });

        tabViewItem.CloseRequested += (_, _) =>
        {
            project.Dispose();
            TaskListTabView.TabItems.Remove(tabViewItem);
        };

        TaskListTabView.TabItems.Add(tabViewItem);
        TaskListTabView.SelectedItem = tabViewItem;
    }
}